var api = require('../config/api.js');
var util = require('../utils/util.js');
var MD5Util = require('../utils/md5.js');
var app = getApp();
//提供接口
module.exports = {
  pay: pay
  }


function pay(orderId, orderType){
  wx.login({
    success: function (res) {
      if (res.code) {
        requestPayParam('234', res.code, orderId, orderType);
      }
      wx.hideLoading()
    }
  });
}

//向服务请求支付参数
function requestPayParam(openId, code, orderId, orderType) {
  
  wx.showLoading({
    title: '加载中...',
    mask: true
  })
  util.request(api.PayPrepayId, { orderId: orderId, openId: openId, code: code, orderType: orderType }).then(function (res) {
    wx.hideLoading();
    if (res.datas.result) {
      //时间戳
      var timestamp = String(Date.parse(new Date()));
      //从服务器请求回来的参数
      let payParam = res.datas;
      // 按照字段首字母排序组成新字符串
      var payDataA = "appId=" + app.globalData.appId + "&nonceStr=" + payParam.nonceStr + "&package=prepay_id=" + payParam.prepayId + "&signType=MD5&timeStamp=" + timestamp;
      var payDataB = payDataA + "&key=" + app.globalData.key;
      // 使用MD5加密算法计算加密字符串
      var paySign = MD5Util.MD5(payDataB).toUpperCase();

      wx.requestPayment({
        'timeStamp': timestamp,
        'nonceStr': payParam.nonceStr,
        'package': "prepay_id=" + payParam.prepayId,
        'signType': "MD5",
        'paySign': paySign,
        'success': function (res) {
          wx.redirectTo({
            url: '/pages/payResult/payResult?status=1&orderId=' + orderId + "&type=" + orderType,
          })
        },
        'fail': function (res) {
          wx.redirectTo({
            url: '/pages/payResult/payResult?status=0&errMsg=' + res.errMsg + "&orderId=" + orderId + "&type=" + orderType,
          })
        }
      })
    } else {
      wx.showToast({
        title: '支付失败',
      })
    }
  });
}